package com.cpecc.dao.system;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.cpecc.model.system.Email;

@Repository
public class EmailDao {

	@Resource
	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public Email getEmail(){
		String hql="from Email";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		if(query.list().size()>0)
			return (Email) query.list().get(0);
		else return null;
	}
	
	public Email getEmail2(){
		String hql="from Email";
		Session session=sessionFactory.openSession();
		Query query=session.createQuery(hql);
		Email email=null;
		if(query.list().size()>0)
			email=(Email) query.list().get(0);
		session.close();
		return email;			
	}
	
	public boolean cover(Email email){
		String hql="update Email t set t.mailServerHost=?,t.mailServerPort=?,t.userName=?,t.password=?,t.fromAddress=? where t.id=?";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, email.getMailServerHost());
		query.setString(1, email.getMailServerPort());
		query.setString(2, email.getUserName());
		query.setString(3, email.getPassword());
		query.setString(4, email.getFromAddress());
		query.setString(5, email.getId());
		return query.executeUpdate()>0;
	}
	
	public void save(Email email){
		Session session=sessionFactory.getCurrentSession();
		session.save(email);
		session.flush();
	}
	
	public Email get(String id){
		return (Email) sessionFactory.getCurrentSession().get(Email.class, id);
	}
}
